package org.zjx.swing.view;

import javax.swing.*;
import java.awt.*;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Base64;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.filechooser.FileFilter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.xml.transform.OutputKeys;

public class InspectView extends JFrame {
    private static final Logger LOGGER = Logger.getLogger(InspectView.class.getName());
    private JTextField[] textFields = new JTextField[3];
    private JTextArea textAreaDescription;
    private JTextArea xmlFilesTextArea = new JTextArea(5, 20);
    private File lastSelectedFile;
    private JLabel imageLabel; // 用于展示图片的标签
    private ArrayList<BufferedImage> images = new ArrayList<>();
    private ArrayList<String> names = new ArrayList<>();
    private ArrayList<String> locations = new ArrayList<>();
    private ArrayList<String> functions = new ArrayList<>();
    private ArrayList<String> descriptions = new ArrayList<>();
    private int currentIndex = 0;
    private JLabel recordedCountLabel; // 新增：已记录道具数量标签
    // 新增：类型标签
    private JLabel typeLabel;
    // 新增：类型下拉框
    private JComboBox<String> typeComboBox;
    // 新增：存储类型的列表
    private ArrayList<String> types = new ArrayList<>();
    private JTextField recordedCountTextField; // 新增：已记录道具数量输入框

    public InspectView() {
        setTitle("道具检验");
        setSize(1200, 600); // 增大窗口宽度以容纳左右面板
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        // 创建左右两个面板
        JPanel leftPanel = new JPanel(new BorderLayout());
        JPanel rightPanel = new JPanel(new FlowLayout());
        rightPanel.setBackground(Color.LIGHT_GRAY); // 为右面板设置背景色以便区分

        // 创建主面板，将原来的内容放入主面板
        JPanel mainPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);

        // 新增：已记录道具数量标签和输入框
        recordedCountLabel = new JLabel("已记录道具数量：");
        recordedCountTextField = new JTextField();
        recordedCountTextField.setEditable(false);

        // 新增：类型标签和下拉框初始化
        typeLabel = new JLabel("类型：");
        String[] options = {"烹饪", "三药", "普通", "任务", "传送","回血","回蓝","复活","装备"};
        typeComboBox = new JComboBox<>(options);

        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 1;
        gbc.fill = GridBagConstraints.NONE;
        gbc.anchor = GridBagConstraints.NORTHWEST;
        mainPanel.add(recordedCountLabel, gbc);

        gbc.gridx = 1;
        gbc.gridwidth = 3;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        mainPanel.add(recordedCountTextField, gbc);

        // 新增：添加类型标签
        gbc.gridx = 0;
        gbc.gridy++;
        gbc.gridwidth = 1;
        gbc.fill = GridBagConstraints.NONE;
        mainPanel.add(typeLabel, gbc);

        // 新增：添加类型下拉框
        gbc.gridx = 1;
        gbc.gridwidth = 3;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        mainPanel.add(typeComboBox, gbc);

        // 文件夹选择按钮
        JButton folderSelectButton = new JButton("选择 XML 文件");
        xmlFilesTextArea.setEditable(false);
        xmlFilesTextArea.setLineWrap(true);
        xmlFilesTextArea.setWrapStyleWord(true);
        xmlFilesTextArea.setVisible(false);

        folderSelectButton.addActionListener(e -> {
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setFileFilter(new FileFilter() {
                @Override
                public boolean accept(File f) {
                    return f.isDirectory() || f.getName().toLowerCase().endsWith(".xml");
                }

                @Override
                public String getDescription() {
                    return "XML Files (*.xml)";
                }
            });
            fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            int result = fileChooser.showOpenDialog(InspectView.this);
            if (result == JFileChooser.APPROVE_OPTION) {
                lastSelectedFile = fileChooser.getSelectedFile();
                xmlFilesTextArea.setText(lastSelectedFile.getName());

                // 隐藏按钮，显示展示框
                folderSelectButton.setVisible(false);
                xmlFilesTextArea.setVisible(true);

                // 清空之前的数据
                images.clear();
                names.clear();
                locations.clear();
                functions.clear();
                descriptions.clear();
                currentIndex = 0;

                // 解析 XML 文件并存储图片和相关信息
                parseXmlFile();
                // 显示第一张图片和信息
                showCurrentImageAndInfo();
            }
        });

        // 添加文件夹选择按钮
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 2;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        mainPanel.add(folderSelectButton, gbc);

        // 添加展示框
        gbc.gridy = 1;
        mainPanel.add(xmlFilesTextArea, gbc);

        // 添加图片展示标签，放在路径下面
        imageLabel = new JLabel();
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.gridwidth = 2;
        gbc.fill = GridBagConstraints.BOTH;
        mainPanel.add(imageLabel, gbc);

        // 新增属性组件
        String[] labels = {"名字", "位置", "作用", "备注"};
        JComponent[] textComponents = new JComponent[4];

        int baseGridY = 3;

        for (int i = 0; i < labels.length; i++) {
            JLabel label = new JLabel(labels[i] + "：");
            JComponent textComponent;

            if (i == 3) {
                textAreaDescription = new JTextArea(3, 20);
                textAreaDescription.setLineWrap(true);
                textAreaDescription.setWrapStyleWord(true);
                textComponent = new JScrollPane(textAreaDescription);
                ((JScrollPane) textComponent).setBorder(BorderFactory.createEtchedBorder());
            } else {
                JTextField textField = new JTextField();
                textField.setPreferredSize(new Dimension(200, 25));
                textField.setMaximumSize(new Dimension(200, 25));
                textComponent = textField;
                textFields[i] = textField;
            }

            gbc.insets = new Insets(0, 10, 0, 5);
            gbc.gridx = 0;
            gbc.gridy = baseGridY + i;
            gbc.gridwidth = 1;
            gbc.fill = GridBagConstraints.NONE;
            gbc.anchor = GridBagConstraints.NORTHWEST;
            mainPanel.add(label, gbc);

            gbc.insets = new Insets(0, 5, 0, 10);
            gbc.gridx = 1;
            gbc.gridwidth = 3;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.anchor = GridBagConstraints.NORTHWEST;
            mainPanel.add(textComponent, gbc);

            textComponents[i] = textComponent;
        }

        // 上一个按钮
        JButton prevButton = new JButton("上一个");
        prevButton.addActionListener(e -> {
            if (currentIndex > 0) {
                currentIndex--;
                showCurrentImageAndInfo();
            }
        });
        gbc.gridx = 0;
        gbc.gridy = baseGridY + labels.length;
        gbc.gridwidth = 1;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        mainPanel.add(prevButton, gbc);

        // 下一个按钮
        JButton nextButton = new JButton("下一个");
        nextButton.addActionListener(e -> {
            if (currentIndex < images.size() - 1) {
                currentIndex++;
                showCurrentImageAndInfo();
            }
        });
        gbc.gridx = 1;
        mainPanel.add(nextButton, gbc);

        // 保存按钮
        JButton saveButton = new JButton("保存");
        saveButton.addActionListener(e -> {
            saveData();
        });
        gbc.gridx = 0;
        gbc.gridy = baseGridY + labels.length + 1;
        gbc.gridwidth = 1;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        mainPanel.add(saveButton, gbc);

        // 删除按钮
        JButton deleteButton = new JButton("删除");
        deleteButton.addActionListener(e -> {
            deleteData();
        });
        gbc.gridx = 1;
        mainPanel.add(deleteButton, gbc);

        // 将主面板添加到左面板
        leftPanel.add(mainPanel, BorderLayout.CENTER);

        // 右面板添加搜索功能
        JTextField searchTextField = new JTextField(20);
        JButton searchButton = new JButton("搜索");
        searchButton.addActionListener(e -> {
            String searchName = searchTextField.getText().trim();
            if (!searchName.isEmpty()) {
                for (int i = 0; i < names.size(); i++) {
                    if (names.get(i).contains(searchName)) {
                        currentIndex = i;
                        showCurrentImageAndInfo();
                        return;
                    }
                }
                JOptionPane.showMessageDialog(this, "未找到匹配的名字", "搜索结果", JOptionPane.INFORMATION_MESSAGE);
            }
        });

        rightPanel.add(new JLabel("按名字搜索:"));
        rightPanel.add(searchTextField);
        rightPanel.add(searchButton);

        // 创建分割面板，将左右面板添加进去
        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, rightPanel);
        splitPane.setDividerLocation(800); // 设置分割线位置

        // 将分割面板添加到窗口
        add(splitPane, BorderLayout.CENTER);
    }


    // 解析 XML 文件并存储图片和相关信息
    private void parseXmlFile() {
        if (lastSelectedFile != null) {
            try {
                DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
                Document doc = docBuilder.parse(lastSelectedFile);

                // 修改为解析 <PropInfo> 节点
                NodeList itemNodes = doc.getElementsByTagName("PropInfo");
                images.clear();
                names.clear();
                locations.clear();
                functions.clear();
                descriptions.clear();
                // 新增：清空类型列表
                types.clear(); 
                for (int i = 0; i < itemNodes.getLength(); i++) {
                    Element itemElement = (Element) itemNodes.item(i);
                    // 获取 <Matrix> 节点
                    Element matrixElement = (Element) itemElement.getElementsByTagName("Matrix").item(0);

                    // 解析图片
                    NodeList imageStringNodes = matrixElement.getElementsByTagName("ImageString");
                    if (imageStringNodes.getLength() > 0) {
                        Element imageStringElement = (Element) imageStringNodes.item(0);
                        String base64Image = imageStringElement.getTextContent();
                        byte[] imageBytes = Base64.getDecoder().decode(base64Image);
                        ByteArrayInputStream bis = new ByteArrayInputStream(imageBytes);
                        BufferedImage image = ImageIO.read(bis);
                        if (image != null) {
                            images.add(image);
                        } else {
                            LOGGER.warning("Failed to read image at index " + i);
                        }
                    } else {
                        LOGGER.warning("No ImageString found at index " + i);
                    }

                    // 解析名字
                    NodeList nameNodes = matrixElement.getElementsByTagName("Name");
                    if (nameNodes.getLength() > 0) {
                        Element nameElement = (Element) nameNodes.item(0);
                        names.add(nameElement.getTextContent());
                    } else {
                        names.add("");
                    }

                    // 解析位置
                    NodeList locationNodes = matrixElement.getElementsByTagName("Position");
                    if (locationNodes.getLength() > 0) {
                        Element locationElement = (Element) locationNodes.item(0);
                        locations.add(locationElement.getTextContent());
                    } else {
                        locations.add("");
                    }

                    // 解析作用
                    NodeList functionNodes = matrixElement.getElementsByTagName("Function");
                    if (functionNodes.getLength() > 0) {
                        Element functionElement = (Element) functionNodes.item(0);
                        functions.add(functionElement.getTextContent());
                    } else {
                        functions.add("");
                    }

                    // 解析备注
                    NodeList descriptionNodes = matrixElement.getElementsByTagName("Description");
                    if (descriptionNodes.getLength() > 0) {
                        Element descriptionElement = (Element) descriptionNodes.item(0);
                        descriptions.add(descriptionElement.getTextContent());
                    } else {
                        descriptions.add("");
                    }
                    // 新增：解析类型
                    NodeList typeNodes = matrixElement.getElementsByTagName("Type");
                    if (typeNodes.getLength() > 0) {
                        Element typeElement = (Element) typeNodes.item(0);
                        types.add(typeElement.getTextContent());
                    } else {
                        types.add("普通");
                    }
                }
            } catch (Exception ex) {
                LOGGER.log(Level.SEVERE, "Error parsing XML file", ex);
                JOptionPane.showMessageDialog(this, "解析 XML 文件时出错。");
            }
        }
    }

    // 显示当前图片和信息
    private void showCurrentImageAndInfo() {
        if (images.size() > 0) {
            BufferedImage originalImage = images.get(currentIndex);
            int width = imageLabel.getWidth();
            int height = imageLabel.getHeight();
            // 如果组件尺寸为 0，使用默认尺寸
            if (width == 0 || height == 0) {
                width = 300;
                height = 300;
            }
            Image scaledImage = originalImage.getScaledInstance(width, height, Image.SCALE_SMOOTH);
            ImageIcon icon = new ImageIcon(scaledImage);
            imageLabel.setIcon(icon);

            textFields[0].setText(names.get(currentIndex));
            textFields[1].setText(locations.get(currentIndex));
            textFields[2].setText(functions.get(currentIndex));
            textAreaDescription.setText(descriptions.get(currentIndex));
            // 新增：设置下拉框选中的类型
            if (types.size() > currentIndex) {
                typeComboBox.setSelectedItem(types.get(currentIndex));
            }
        }
        // 新增：更新已记录道具数量输入框的值
        recordedCountTextField.setText(String.valueOf(images.size()));
    }

    // 保存数据到 XML 文件
    private void saveData() {
        if (lastSelectedFile == null) {
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setFileFilter(new FileFilter() {
                @Override
                public boolean accept(File f) {
                    return f.isDirectory() || f.getName().toLowerCase().endsWith(".xml");
                }

                @Override
                public String getDescription() {
                    return "XML Files (*.xml)";
                }
            });
            int result = fileChooser.showSaveDialog(this);
            if (result == JFileChooser.APPROVE_OPTION) {
                lastSelectedFile = fileChooser.getSelectedFile();
                if (!lastSelectedFile.getName().toLowerCase().endsWith(".xml")) {
                    lastSelectedFile = new File(lastSelectedFile.getAbsolutePath() + ".xml");
                }
            } else {
                return;
            }
        }

        // 更新内存中的数据
        names.set(currentIndex, textFields[0].getText());
        locations.set(currentIndex, textFields[1].getText());
        functions.set(currentIndex, textFields[2].getText());
        descriptions.set(currentIndex, textAreaDescription.getText());
        // 确保更新类型数据
        types.set(currentIndex, (String) typeComboBox.getSelectedItem()); 

        try {
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.newDocument();

            // 创建根节点
            Element rootElement = doc.createElement("PropInfoList");
            doc.appendChild(rootElement);

            for (int i = 0; i < images.size(); i++) {
                // 创建 PropInfo 节点
                Element propInfoElement = doc.createElement("PropInfo");
                rootElement.appendChild(propInfoElement);

                // 创建 Matrix 节点
                Element matrixElement = doc.createElement("Matrix");
                propInfoElement.appendChild(matrixElement);

                // 保存位置
                Element positionElement = doc.createElement("Position");
                positionElement.setTextContent(locations.get(i));
                matrixElement.appendChild(positionElement);

                // 保存名字
                Element nameElement = doc.createElement("Name");
                nameElement.setTextContent(names.get(i));
                matrixElement.appendChild(nameElement);

                // 保存作用
                Element functionElement = doc.createElement("Function");
                functionElement.setTextContent(functions.get(i));
                matrixElement.appendChild(functionElement);

                // 保存备注
                Element descriptionElement = doc.createElement("Description");
                descriptionElement.setTextContent(descriptions.get(i));
                matrixElement.appendChild(descriptionElement);

                // 保存类型
                Element typeElement = doc.createElement("Type");
                typeElement.setTextContent(types.get(i));
                matrixElement.appendChild(typeElement);

                // 保存图片
                BufferedImage image = images.get(i);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ImageIO.write(image, "png", baos);
                byte[] imageBytes = baos.toByteArray();
                String base64Image = Base64.getEncoder().encodeToString(imageBytes);

                Element imageStringElement = doc.createElement("ImageString");
                imageStringElement.setTextContent(base64Image);
                matrixElement.appendChild(imageStringElement);
            }

            // 将 Document 写入文件
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new FileOutputStream(lastSelectedFile));
            transformer.transform(source, result);

            JOptionPane.showMessageDialog(this, "保存成功");
        } catch (ParserConfigurationException | TransformerException | IOException ex) {
            LOGGER.log(Level.SEVERE, "Error saving XML file", ex);
            JOptionPane.showMessageDialog(this, "保存文件时出错。");
        }
    }

    // 删除当前数据对应的 XML 节点
    private void deleteData() {
        if (lastSelectedFile == null) {
            JOptionPane.showMessageDialog(this, "请先选择 XML 文件");
            return;
        }
        if (images.size() == 0) {
            JOptionPane.showMessageDialog(this, "没有可删除的数据");
            return;
        }

        try {
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(lastSelectedFile);

            NodeList propInfoNodes = doc.getElementsByTagName("PropInfo");
            if (currentIndex < propInfoNodes.getLength()) {
                Element propInfoToRemove = (Element) propInfoNodes.item(currentIndex);
                propInfoToRemove.getParentNode().removeChild(propInfoToRemove);

                // 保存修改后的 XML 文件
                TransformerFactory transformerFactory = TransformerFactory.newInstance();
                Transformer transformer = transformerFactory.newTransformer();
                transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                DOMSource source = new DOMSource(doc);
                StreamResult result = new StreamResult(new FileOutputStream(lastSelectedFile));
                transformer.transform(source, result);

                JOptionPane.showMessageDialog(this, "删除成功");
            }
        } catch (Exception ex) {
            LOGGER.log(Level.SEVERE, "Error deleting data from XML file", ex);
            JOptionPane.showMessageDialog(this, "删除数据时出错。");
        }
    }

    // 刷新数据
    private void refreshData() {
        if (lastSelectedFile != null) {
            images.clear();
            names.clear();
            locations.clear();
            functions.clear();
            descriptions.clear();
            currentIndex = 0;
            parseXmlFile();
            showCurrentImageAndInfo();
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            InspectView inspectView = new InspectView();
            inspectView.setVisible(true);
        });
    }
}
